package com.lz.twosum;

import java.util.HashMap;
import java.util.Map;

public class TwoSum {

    /**
     * 有序数组 两数之和等于目标值
     *
     * @param nums
     * @param target
     * @return
     */
    int[] twoSumSorted(int[] nums, int target) {

        int i = 0, j = nums.length - 1;

        while (i < j) {
            int x = nums[i] + nums[j];
            if (x == target) return new int[]{i, j};
            else if (x > target) j--;
            else i++;
        }
        return null;
    }

    /**
     * 无序 两数之和等于目标值
     *
     * @return
     */

    boolean twoSumUnSorted(int[] nums, int target) {

        Map<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];

            Integer first = map.getOrDefault(num, 0);
            map.put(num, first + 1);

            int second = target - num;
            if (second == num && first == 1) return true;
            if (map.containsKey(second)) return true;
        }
        return false;
    }

}
